const OSS = require('ali-oss')
const log = require('../log')
const packageJson = require('../package.json')

const UPLOAD = {}

UPLOAD.client = (options) => {
  return new OSS({
    region: options.region,
    accessKeyId: options.accessKeyId,
    accessKeySecret: options.accessKeySecret,
    bucket: options.bucket,
    secure: true // https
  })
}

// 上传
UPLOAD.upload = async(file, options, fileName) => {
  try {
    const result = await UPLOAD.client(options).put(fileName, file.path)
    log.green(`Upload Success ${result.url}`)
  } catch (err) {
    log.red(`${packageJson.name} Upload Error ${options.prefix}/${fileName}`)
    log.red(`${packageJson.name} Upload Error>> ${err}`)
  }
}

/**
 * 获取指定前缀的文件列表
 * @param {Object} options 配置
 * @param {Object} params 参数
 *  prefix             string        列举符合特定前缀的文件。
 *  delimiter          string        对文件名称进行分组的字符。
 *  marker             string        列举文件名在marker之后的文件。
 *  max-keys           number|string 指定最多返回的文件个数。
 *  encoding-type      'url'|''      对返回的内容进行编码并指定编码类型为URL。
 * @param {Function} callback 回调
 */
UPLOAD.get = async(options, params, callback) => {
  try {
    const result = await UPLOAD.client(options).list(params)
    callback(result)
  } catch (err) {
    log.red(`${packageJson.name} Get Error>> ${err}`)
  }
}

/**
 * 删除
 * @param {Object} options 配置
 * @param {String} fileName 文件地址列表
 */
UPLOAD.delete = async(options, fileName) => {
  try {
    const getResult = await UPLOAD.client(options).delete(fileName)
    log.yellow(`Delete Success ${options.prefix}/${fileName}`)
  } catch (err) {
    log.red(`${packageJson.name} Delete Error>> ${err}`)
  }
}

module.exports = UPLOAD
